import type { App } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { useNProgress } from '@/hooks/useNProgress'
import { useUserStoreWithOut } from '@/store/modules/user'
import { createRouter, createWebHistory } from 'vue-router'
import { constantRouterMap } from './routeTree'

// 创建router
const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_APP_CONFIG_BASE ?? '/'),
  strict: true,
  routes: constantRouterMap as RouteRecordRaw[],
  scrollBehavior: () => ({ left: 0, top: 0 }),
})

const { start, done } = useNProgress()

const whiteList = ['/login', '/dashboard'] // 不重定向白名单

router.beforeEach(async (to, from, next) => {
  start()
  const userStore = useUserStoreWithOut()
  if (userStore.getUserInfo) {
    if (to.path === '/login') {
      next({ path: '/' })
    }
    else {
      next()
    }
  }
  else {
    if (whiteList.includes(to.path))
      next()
    else next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
  }
})

router.afterEach((to) => {
  done() // 结束Progress
})

export { router }

export function setupRouter(app: App<Element>) {
  app.use(router)
}
